var developmentName = {
    fireplace: "火炉",
    cookingHearth: "灶台",
    stoneOven:"石造烤炉",
    brickOven:"砖石烤炉",
    potteryWorkshop: "陶器工坊",
    basketryWorkshop: "制篮工坊",
    carpentryWorkshop: "木工坊",
    well: "井"
}

const developmentIdMap = {
    fireplace: ["major-development-fireplace", "major-development-fireplace1"],
    cookingHearth: ["major-development-cooking-hearth", "major-development-cooking-hearth1"],
    stoneOven: ["major-development-stone-oven"],
    brickOven: ["major-development-brick-oven"],
    potteryWorkshop: ["major-development-pottery-workshop"],
    basketryWorkshop: ["major-development-basketry-workshop"],
    carpentryWorkshop: ["major-development-carpentry-workshop"],
    well: ["major-development-well"]
};

// 将发展卡名和subtype编号映射为对应div的class名
function getDevelopmentId(development, subtype) {
    let ids = developmentIdMap[development];
    return ids && ids[subtype] ? ids[subtype] : null;
}

async function selectDevelopmentCard(status = "developmentCard") {
    window.actionData.status = status;
    window.actionData.substatus = ["majorDevelopmentCard", "minorDevelopmentCard"];

    updateAdditionalView();

    $("#display-major-development-btn").css("display", "none");

    if (status == "developmentCard") {
        window.myData.unusedWorker -= 1;
        let workSpaceKey = "development-card";
        appendWorkerToTitle(workSpaceKey);
        await dispatchEvent(EVENT_USE_TURN_ACTION_BEFORE, { workSpaceKey });
    }
}

async function selectMajorDevelopment(development, subtype) {
    if (!hasSubstatus("majorDevelopmentCard")) {
        return;
    }

    if (!confirm(`确定选择"${developmentName[development]}"？`)) {
        return;
    }

    // 检查资源是否足够
    var cost = getMajorDevelopmentCost(development, subtype);

    // 检查玩家是否已有火炉
    const fireplaceIndex = window.myData.developmentCards.findIndex(card => card.type === 'fireplace');

    if (development === 'cookingHearth' && fireplaceIndex !== -1) {
        if (confirm('你已有火炉，是否归还以抵扣建造灶台的花费？')) {
            // 移除一个火炉
            const removedFireplace = window.myData.developmentCards.splice(fireplaceIndex, 1)[0];
            // 显示主要发展卡列表中对应的火炉卡片
            const fireplaceId = getDevelopmentId('fireplace', removedFireplace.subtype);
            if (fireplaceId) {
                $(`#${fireplaceId}`).show();
            }
            // 移除已建造的火炉卡片节点
            $(`#card-container .card:contains(${developmentName['fireplace']})`).remove();
            // 归还火炉，建造灶台无需花费
            cost = { wood: 0, clay: 0, reed: 0, stone: 0 }; // 表示免费
        }
    }

    if (!hasEnoughResources(cost)) {
        alert("资源不足，无法建造该主要发展卡！");
        return;
    }

    // 扣除资源
    deductResources(cost);

    // 保存主要发展卡到个人数据中
    addDevelopmentCard(development, subtype);

    // 添加主要发展卡UI
    addMajorDevelopmentCardNode(development, subtype);

    // 触发主要发展卡立即结算的效果
    await applyMajorDevelopment(development, subtype);

    window.actionData.substatus.push("playedOneCard");

    // 完成发展卡阶段
    endDevelopmentCard();
}

function getMajorDevelopmentCost(development, subtype = 0) {
    // 返回建造该主要发展卡所需的资源
    const costs = {
        "fireplace": [
            {wood: 0, clay: 2, reed: 0, stone: 0}, // subtype 0
            {wood: 0, clay: 3, reed: 0, stone: 0}  // subtype 1
        ],
        "cookingHearth": [
            {wood: 0, clay: 4, reed: 0, stone: 0}, // subtype 0
            {wood: 0, clay: 5, reed: 0, stone: 0}  // subtype 1
        ],
        "stoneOven": [{wood: 0, clay: 1, reed: 0, stone: 3}], // only one subtype
        "brickOven": [{wood: 0, clay: 3, reed: 0, stone: 1}], // only one subtype
        "potteryWorkshop": [{wood: 0, clay: 2, reed: 0, stone: 2}],
        "basketryWorkshop": [{wood: 0, clay: 0, reed: 2, stone: 2}],
        "carpentryWorkshop": [{wood: 2, clay: 0, reed: 0, stone: 2}],
        "well": [{wood: 1, clay: 0, reed: 0, stone: 3}]
    };

    const developmentCosts = costs[development];
    if (!developmentCosts) {
        console.error("Development not recognized:", development);
        return null;
    }

    return developmentCosts[subtype] || developmentCosts[0]; // Default to subtype 0 if requested subtype does not exist
}


function hasEnoughResources(cost) {
    // 检查当前资源是否足够支付cost
    if (!cost) return false; // If cost object is null or undefined, return false

    // Check if the player has enough resources for each type
    return Object.entries(cost).every(([resource, amount]) => {
        return window.myData[resource] >= amount; // Compare each required resource with the player's resources
    });
}

function deductResources(cost) {
    // 扣除建造发展卡所需的资源
    if (!cost) return; // 如果没有提供成本信息，直接返回

    // 遍历成本对象，从玩家资源中扣除相应的数量
    Object.entries(cost).forEach(([resource, amount]) => {
        if (window.myData[resource] !== undefined) { // 确保资源存在于玩家数据中
            window.myData[resource] -= amount;
        }
    });

}

// 添加发展卡
function addDevelopmentCard(type, subtype) {
    window.myData.developmentCards.push({ type: type, subtype: subtype });
}

function addMajorDevelopmentCardNode(development, subtype) {
    // 应用主要发展卡的效果
    if (development == "fireplace" || development == "cookingHearth") {
        addFireplaceOrCookingHearthCardNode(development);
    } else if (development == "stoneOven" || development == "brickOven") {
        addOvenCardNode(development);
    } else if (development == "potteryWorkshop" || development == "basketryWorkshop" || development == "carpentryWorkshop") {
        addWorkshopCardNode(development);
    } else if (development == "well") {
        addWellCardNode()
    }
    
    // 根据映射获取对应的ID并隐藏对应的div
    let divId = getDevelopmentId(development, subtype);
    if (divId) {
        $(`#${divId}`).hide();
    }
}

async function applyMajorDevelopment(development, subtype) {
    if (development == "well") {
        activateWellEffect();
    } else if (development === "stoneOven" || development === "brickOven") {
        await startBakeBread();
    }
}

function endDevelopmentCard() {
    $("#display-major-development-btn").css("display", "inline-block");

    endAction();
}

function addFireplaceOrCookingHearthCardNode(selectedDevelopment) {
    var exchangeRates = {
        fireplace: { 
            scores: 1, // 火炉的分数
            always: {vegetable: 2, pig: 2, sheep: 2, cattle: 3}, // 任何时候可用的兑换率
            bread: {grain: 2} // 烤面包时可用的兑换率
        },
        cookingHearth: {
            scores: 1, // 灶台的分数
            always: {vegetable: 3, pig: 3, sheep: 2, cattle: 4}, // 任何时候可用的兑换率
            bread: {grain: 3} // 烤面包时可用的兑换率
        }
    };

    var cardInfo = exchangeRates[selectedDevelopment];
    var $cardContainer = $('#card-container');
    var $card = $('<div/>', {
        class: 'card'
    }).appendTo($cardContainer);

    // 创建卡片标题并包含分数
    var $cardTitle = $('<div/>', {
        class: 'card-header',
        html: `${developmentName[selectedDevelopment]} <span class="card-score">分数：${cardInfo.scores}</span>`
    }).appendTo($card);

    // 创建卡片内容容器
    var $cardBody = $('<div/>', {
        class: 'card-body'
    }).appendTo($card);

    // 添加“任何时候可用”的按钮
    var $alwaysSection = $('<div/>', {
        class: 'action-section',
        html: '<h4>在任何时候：</h4>'
    }).appendTo($cardBody);

    $.each(cardInfo.always, function(type, rate) {
        $('<button/>', {
            text: `1${TypeName[type]} -> ${rate}食`,
            class: 'action-button',
            click: function() { exchange(type, rate); }
        }).appendTo($alwaysSection);
    });

    // 添加“烤面包时可用”的按钮
    var $breadSection = $('<div/>', {
        class: 'action-section',
        html: '<h4>烤面包：</h4>'
    }).appendTo($cardBody);

    $.each(cardInfo.bread, function(type, rate) {
        $('<button/>', {
            text: `1${TypeName[type]} -> ${rate}食`,
            class: 'action-button',
            click: function() { bakeBread(type, rate); }
        }).appendTo($breadSection);
    });

    $cardContainer.show();  // 显示卡片容器
}

function addOvenCardNode(ovenType) {
    var exchangeRates = {
        stoneOven: {
            scores: 3, // 石造烤炉的分数
            bread: { 
                grain: 4,  // 烤面包时可用的兑换率, 
                times: 2 // 一次烤面包行动可执行的兑换次数
            }
        },
        brickOven: {
            scores: 2, // 砖石烤炉的分数
            bread: { 
                grain: 5,  // 烤面包时可用的兑换率
                times: 1 // 一次烤面包行动可执行的兑换次数
            } 
        }
    };

    var cardInfo = exchangeRates[ovenType];
    var $cardContainer = $('#card-container');
    var $card = $('<div/>', {
        class: 'card'
    }).appendTo($cardContainer);

    // 创建卡片标题并包含分数
    var $cardTitle = $('<div/>', {
        class: 'card-header',
        html: `${developmentName[ovenType]} <span class="card-score">分数：${cardInfo.scores}</span>`
    }).appendTo($card);

    // 创建卡片内容容器
    var $cardBody = $('<div/>', {
        class: 'card-body'
    }).appendTo($card);

    // 添加"烤面包时可用"的按钮
    var $breadSection = $('<div/>', {
        class: 'action-section',
        html: `<h4>烤面包：${cardInfo.bread.times}x</h4>`
    }).appendTo($cardBody);

    $.each(cardInfo.bread, function(type, rate) {
        if (TypeName[type] != undefined) {
            $('<button/>', {
                text: `1${TypeName[type]} -> ${rate}食`,
                class: 'action-button',
                click: function() { bakeBread(type, rate); }
            }).appendTo($breadSection);
        }
    });

    $cardContainer.show();  // 显示卡片容器
}

function addWorkshopCardNode(development) {
    const cardDetails = {
        "potteryWorkshop": {
            scores: 2,
            harvest: {clay: {amount: 1, food: 2}},
            scoring: {clay: {thresholds: [3, 5, 7], points: [1, 2, 3]}}
        },
        "basketryWorkshop": {
            scores: 2,
            harvest: {reed: {amount: 1, food: 3}},
            scoring: {reed: {thresholds: [2, 4, 5], points: [1, 2, 3]}}
        },
        "carpentryWorkshop": {
            scores: 2,
            harvest: {wood: {amount: 1, food: 2}},
            scoring: {wood: {thresholds: [3, 5, 7], points: [1, 2, 3]}}
        }
    };

    const cardInfo = cardDetails[development];
    if (!cardInfo) {
        console.error("No card information available for:", development);
        return;
    }

    var $cardContainer = $('#card-container');
    var $card = $('<div/>', { class: 'card' }).appendTo($cardContainer);
    var $cardHeader = $('<div/>', {
        class: 'card-header',
        html: `${developmentName[development]} <span class="card-score">分数：${cardInfo.scores}</span>`
    }).appendTo($card);
    var $cardBody = $('<div/>', { class: 'card-body' }).appendTo($card);

    // 添加收成转换功能
    var $harvestSection = $('<div/>', { class: 'action-section', html: '<h4>收成时：1x</h4>' }).appendTo($cardBody);
    Object.entries(cardInfo.harvest).forEach(([resource, {amount, food}]) => {
        $('<button/>', {
            text: `${amount}${TypeName[resource]} -> ${food}食`,
            class: 'action-button',
            click: function() { exchange(resource, food); }
        }).appendTo($harvestSection);
    });

    // 添加计分规则
    var $scoringSection = $('<div/>', { class: 'action-section', html: '<h4>计分时：</h4>' }).appendTo($cardBody);
    Object.entries(cardInfo.scoring).forEach(([resource, {thresholds, points}]) => {
        $('<button/>', {
            text: `${thresholds.join('/')}${TypeName[resource]} -> ${points.join('/')}分`,
            class: 'action-button',
            click: function() { exchangeResourcesForPointsBeforeFinalScore(resource, thresholds, points); }
        }).appendTo($scoringSection);
    });

    $cardContainer.show();
}

function activateWellEffect() {
    operateRoundRewardsForNextXRounds(5, (roundIndex) => {
        const oldValue = window.myData.roundRewards[roundIndex].food || 0;
        window.myData.roundRewards[roundIndex].food = oldValue + 1;
    });
}

function addWellCardNode() {

    const wellInfo = {
        scores: 4,
    };

    var $cardContainer = $('#card-container');
    var $card = $('<div/>', { class: 'card' }).appendTo($cardContainer);
    var $cardHeader = $('<div/>', {
        class: 'card-header',
        html: `${developmentName.well} <span class="card-score">分数：${wellInfo.scores}</span>`
    }).appendTo($card);
    var $cardBody = $('<div/>', { class: 'card-body' }).appendTo($card);

    // 添加当前水井效果详情
    var $wellEffectSection = $('<div/>', { class: 'action-section' }).appendTo($cardBody);
    $('<h4/>', { text: '水井效果：' }).appendTo($wellEffectSection);
    $('<p/>', { 
        text: `在接下来5轮的轮次格上各放置1个食物。在这些轮开始时，你从该格子上拿取放置的食物。`,
    }).appendTo($wellEffectSection);

    $cardContainer.show();  // 显示卡片容器
}

// 恢复显示发展卡，用于读档
function restoreDevelopmentCards() {
    window.myData.developmentCards.forEach(card => {
        const { type, subtype } = card;
        addMajorDevelopmentCardNode(type, subtype);
    });
}

// 主要发展卡列表下方的提示语的更新方法
function updateMajorDevelopmentPromptView() {
    $(".major-development-prompt-view-title").text("你可以打出一张 主要 或 次要 发展卡。");
}

function updateMajorDevelopmentPromptViewForDisplay() {
    $(".major-development-prompt-view-title").text("当前仅展示主要发展卡。");
}